/*   
 * Copyright (C) 2015 O. Wu
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.osx.my2048.view;

import java.awt.Color;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JLabel;

/**
 * 
 * This class is the base block of the game board, each block represent a value
 * from 0 to 4096, if the block's value equals 0, then it's value will be
 * invisible.
 * 
 * This class is forged according to jinhu's Block.java, many thanks. :)
 * 
 * http://www.oschina.net/code/snippet_1779389_36129
 * http://www.java3z.com/cwbwebhome/article/article5/50442.html
 * 
 * @author O. Wu
 * @date 15/02/18
 */
public class Block extends JLabel {

	private static final long serialVersionUID = 4535604860326281726L;

	/** The value-color map. */
	private static Map<Integer, Color> map;

	// Initialize the color map
	static {
		map = new HashMap<Integer, Color>();
		map.put(0, Color.gray);
		map.put(2, new Color(238, 228, 218));
		map.put(4, new Color(238, 224, 198));
		map.put(8, new Color(243, 177, 116));
		map.put(16, new Color(243, 177, 116));
		map.put(32, new Color(248, 149, 90));
		map.put(64, new Color(249, 94, 50));
		map.put(128, new Color(239, 207, 108));
		map.put(256, new Color(239, 207, 99));
		map.put(512, new Color(239, 203, 82));
		map.put(1024, new Color(239, 199, 57));
		map.put(2048, new Color(239, 195, 41));
		map.put(4096, new Color(255, 60, 57));
	}

	/** The value of the block. */
	private int value;

	public Block() {
		this(0);
	}

	public Block(int value) {
		setValue(value);
		this.setFont(new Font("font", Font.PLAIN, 40));
		this.setHorizontalAlignment(CENTER);
		this.setOpaque(true);
	}

	/**
	 * Return the value of the block.
	 */
	public int value() {
		return value;
	}

	/**
	 * Return the value of block list as an array.
	 */
	public static int[] valueArray(java.util.List<Block> list) {
		int[] array = new int[list.size()];

		for (int i = 0; i < array.length; i++) {
			array[i] = list.get(i).value;
		}

		return array;
	}

	/**
	 * Set a new value.
	 */
	public void setValue(int value) {
		this.value = value;
		String text = String.valueOf(value);

		// If the value equals 0, then it's value will be invisible
		if (value != 0) {
			this.setText(text);
		} else {
			this.setText("");
		}
		this.setBackground(map.get(value));
	}
}
